//识别结果，批量识别
<template>
  <div class="box">
    <br /><br /><br />
    <div class="top-left">
      <!-- <el-card> -->
      <h3 style="display: inline-block;">输入量：{{ total }}</h3>
      <el-button
      @click="btn"
      type="success"
      style="
        width: 110px;
        height: 40px;
        border: 0px;
        font-size: 17px;
        color: aliceblue;
        /* position: relative; */
        margin-left: -90px;
        float: right;
        /* margin-top: px; */
        bottom: 17px;
      "
      ><div style="color: aliceblue;">重新上传</div></el-button
    >
      <!-- <h3>识别结果:</h3> -->
      <div
        class="right-img"
        v-loading="loading"
        element-loading-text="拼命识别中"
      >
        <div
          id="div-img"
          :style="styleObj"
          ref="ref1"
          v-for="(img, index) in imgs"
          :key="index"
        >
          <!-- <img :src="img['path']+'&tempid='+Math.random()" class="imgs" /> -->
          <img :src="img['path']" class="imgs" />
          <!-- 病害名称 -->
          <h4 v-text="img['disease']" class="diseases"></h4>
        </div>
      </div>
    </div>
    <div class="top-right">
      <el-card class="box-card">
        <div class="clearfix">
          <span>总耗时：</span>
          <h3 class="h23">{{ time }}ms</h3>
        </div>
        <div class="clearfix">
          <br /><br />
          <span>平均耗时：</span>
          <!-- toFixed(0)保留0位小数 -->
          <h3 class="h23">{{ (time / total).toFixed(0) }}ms</h3>
        </div>
      </el-card>
    </div>
    <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    <input
      type="file"
      multiple
      ref="ref2"
      style="display: none"
      @change="onFileChanges"
    />
    <!-- <el-button
      @click="btn"
      type="success"
      style="
        width: 110px;
        height: 40px;
        border: 0px;
        font-size: 17px;
        color: aliceblue;
        position: relative;
        margin-left: 40px;
        margin-top: 80px;
        bottom: 17px;
      "
      >重新上传</el-button
    > -->
    <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
    <div
      class="echarts"
      id="echarts"
      v-loading="loading"
      element-loading-text="拼命识别中"
    >
      <h2 style="margin-top: -10px;">
        识别结果:<el-button
          style="margin-left: 927px;color:aliceblue"
          type="success"
          size="mini" 
          @click="takephotos"
          ><div style="color: aliceblue;"> 导出识别结果</div></el-button
        >
      </h2>
      <div class="echarts-li" id="curve_show"></div>
      <div class="echarts-li" style="width: 450px" id="pie_show"></div>
      <div class="echarts-li" id="column_show"></div>
      <el-button
        type="success"
        size="mini"
        @click="download"
        :loading="flag"
        style="margin-left: 500px"
        ><div style="color: aliceblue;">下载分类结果</div></el-button
      >
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts";
import $ from "jquery";
//请入批量预测请求方法，以及下载方法
import { predict_batch, download } from "@/api/index";
//引入截图方法
import html2canvas from "html2canvas";
export default {
  data() {
    return {
      histogram: {},
      imgs: [],
      pieChart: {},
      radarMap: [],
      total: 1,
      time: 0,
      loading: true,
      flag: false,
      path: "",
      styleObj: {
        width: "",
        position: "relative",
      },
    };
  },
  mounted() {
    this.initfn();
  },
  methods: {
    btn() {
      //打开识别
      this.$refs.ref2.click(); // 模拟点击
    },
    //多个图片选择
    onFileChanges(e) {
      const files = e.target.files;
      if (files.length > 0) {
        this.loading = true;
        this.$store.commit("setData", files);
        this.initfn();
      }
    },
    // 识别，展示统计图
    async initfn() {
      let files = this.$store.state.imgs; //此时是文件数组
      // let files = this.imgs;
      // console.log("===========================");
      // console.log(files);
      if (files.length > 0) {
        // $("#div-img").css("width",this.$store.state.imgs.length*100)
        // console.log(this.$store.state.imgs.length*100)
        // console.log(this.$refs.ref1.width)
        let formData = new FormData();
        for (let i = 0; i < files.length; i++) {
          formData.append("file", files[i]);
        }
        //时间戳，毫秒数
        let startTime = new Date().getTime();

        await predict_batch(formData).then((res) => {
          let endTime = new Date().getTime();
          this.time = endTime - startTime;
          // console.log("res.data=======" + JSON.stringify(res.data));
          let result = JSON.parse(JSON.stringify(res.data));
          if (result.code == 0) {
            let data = result.data;
            this.histogram = data.histogram;
            this.imgs = data.imgs;
            this.pieChart = data.pieChart;
            this.radarMap = data.radarMap;
            this.total = data.total;
            this.path = data.path;
            this.path = data.path;
            this.styleObj.width = this.$store.state.imgs.length * 190 + "px";
            console.log(this.styleObj.width);
            this.initCurve();
            this.initPie();
            this.initColumn();
            this.loading = false;

            this.$notify.success({
              title: "Info",
              message: "识别成功！",

              showClose: false,
            });
          } else {
            this.$notify.error({
              title: "错误",
              message: result.message,
            });
          }
        });
      } else {
        this.$notify.error({
          title: "错误",
          message: "图片丢失！",
        });
      }
    },
    // 下载
    async download() {
      this.flag = true; //打开按钮转圈效果
      await download(this.path).then((res) => {
        const url = window.URL.createObjectURL(res.data);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = "识别结果.zip"; // 文件重命名，若无需重命名，将该行删去
        link.click();
        URL.revokeObjectURL(url); // 释放内存
      });
      this.flag = false; //关闭按钮转圈效果
      this.$notify.success({
        title: "Info",
        message: "识别结果导出成功！",
        showClose: false,
      });
    },
    // 导出统计图
    async takephotos() {
      let echarts = document.getElementById("echarts");
      await html2canvas(echarts, {
        //一些参数，进行设置
        useCORS: true,
        width: 1200,
        height: 400,
        scale: 4,
        allowTaint: false,
      }).then((canvas) => {
        //回调函数
        let url = canvas.toDataURL("image/png");
        // console.log("url=" + url);
        var $a = document.createElement("a"); //创建a标签
        $a.download = "识别结果.png"; //对a标签设置以下属性
        $a.target = "_blank";
        $a.href = url;
        if (typeof MouseEvent === "function") {
          //点击事件
          var evt = new MouseEvent("click", {
            view: window,
            bubbles: true,
            cancelable: false,
          });
          $a.dispatchEvent(evt);
        }
      });
      this.$notify.success({
        title: "Info",
        message: "识别结果导出成功！",
        showClose: false,
      });
    },
    //更新柱状图
    initCurve() {
      var myChart = echarts.init(document.getElementById("curve_show"));
      myChart.setOption({
        title: {
          text: "各病害类别图片数量",
          left: "center",
        },
        color: ["#54924b", "#54924b", "#54924b"],
        //鼠标悬停显示
        tooltip: {
          trigger: "item",
          formatter: "{a} ：<br/>{b}: {c}张",
        },
        xAxis: {
          name: "病害类型",
          data: this.histogram.disease,
        },
        yAxis: {
          type: "value",
          name: "图片数量",
          // axisLabel: {
          //   formatter: "{value}%",
          // },
        },
        series: [
          {
            name: "图片数量",
            type: "bar",
            barWidth: "50%",
            data: this.histogram.num,
            itemStyle: {
              normal: {
                label: {
                  show: true, //开启显示
                  position: "top", //在上方显示
                  textStyle: {
                    //数值样式
                    color: "black",
                    fontSize: 12,
                  },
                  formatter: "{c}张",
                },
              },
            },
          },
        ],
      });
    },
    //更新饼状图
    initPie() {
      var myChart3 = echarts.init(document.getElementById("pie_show"));
      myChart3.setOption({
        title: {
          text: "各病害占比",
          left: "center",
        },
        //鼠标悬停显示
        tooltip: {
          trigger: "item",
          formatter: "{a}：<br/>{b}: {c}%",
        },
        // legend: {
        //   data: ["Direct", "Marketing", "Search Engine"],
        // },
        series: [
          {
            name: "病害占比",
            type: "pie", //重点
            center: ["50%", "50%"],
            radius: "40%", //半径
            label: {
              normal: {
                formatter: "{b}:{c}%",
                textStyle: {
                  fontWeight: "normal",
                  fontSize: 12,
                },
              },
            },

            // itemStyle: {
            //   emphasis: {
            //     shadowBlur: 10,
            //     shadowOffsetX: 0,
            //     shadowColor: "rgba(0, 0, 0, 0.5)",
            //   },
            // },
            // radius: ["50%", "8%"],
            // labelLine: {
            //   length: 30,
            // },
            // label: {
            //   formatter: "{a|{a}}{abg|}\n{hr|}\n  {b|{b}:}{c}   ",
            //   backgroundColor: "#F6F8FC",
            //   borderColor: "#8C8D8E",
            //   borderWidth: 1,
            //   borderRadius: 4,
            //   rich: {
            //     a: {
            //       color: "#6E7079",
            //       lineHeight: 22,
            //       align: "center",
            //     },
            //     hr: {
            //       borderColor: "#8C8D8E",
            //       width: "100%",
            //       borderWidth: 1,
            //       height: 0,
            //     },
            //     b: {
            //       color: "#4C5058",
            //       fontSize: 14,
            //       fontWeight: "bold",
            //       lineHeight: 30,
            //     },
            //   },
            // },
            data: this.pieChart,
          },
        ],
      });
    },
    //更新雷达图
    initColumn() {
      var myChart4 = echarts.init(document.getElementById("column_show"));
      myChart4.setOption({
        title: {
          text: "置信度分布范围",
          left: "center",
        },
        color: ["#54924b", "#54924b", "#54924b", "#54924b", "#54924b"],
        tooltip: {
          trigger: "axis",
        },
        // //鼠标悬停显示
        // tooltip: {
        //   trigger: "axis",
        //   formatter: "{a}：<br/>{b}: {c}%",
        //   // formatter: "{c}%",
        // },
        legend: {
          left: "center",
          data: [],
        },
        radar: [
          {
            indicator: [
              { text: "0-80", max: this.total / 2 },
              { text: "80-85", max: this.total / 2 },
              { text: "85-90", max: this.total / 2 },
              { text: "90-95", max: this.total / 2 },
              { text: "95-100", max: this.total },
            ],
            radius: 80,
            center: ["50%", "60%"],
          },
        ],
        series: [
          {
            type: "radar",
            tooltip: {
              trigger: "item",
            },
            areaStyle: {},
            data: [
              {
                value: this.radarMap,
                name: "置信度分布范围",
                //这里的配置显示数值
                label: {
                  normal: {
                    show: true,
                    formatter: function (params) {
                      return params.value;
                    },
                  },
                },
              },
            ],
          },
        ],
      });
    },
  },
};
</script>
<style scoped>
.box {
  width: 1200px;
  height: 900px;
  background-color: rgb(255, 255, 255);
  margin-top: -80px;
}
.top-left {
  width: 750px;
  height: 300px;
  background-color: rgb(255, 255, 255);
  float: left;
  margin-left: 70px;
  box-shadow: 0px 0px 100px 0px rgb(236, 236, 236);
  margin-top: 30px;
  border: 1px solid rgb(245, 245, 245);
  /* overflow-x: hidden; */
  /* overflow-y: hidden; */
}
.h23 {
  text-align: center;
}

.top-right {
  width: 250px;
  height: 280px;
  background-color: rgb(233, 224, 224);
  margin-left: 60px;
  float: left;
  margin-top: 30px;
}

.echarts {
  width: 1190px;
  height: 400px;
  background-color: rgb(232, 232, 232);
  margin-top: -90px;
  margin-left: 20px;
}
.echarts-li {
  width: 370px;
  height: 370px;
  background-color: rgb(255, 255, 255);
  float: left;
  margin-top: -20px;
}
.right-img {
  width: 750px;
  height: 250px;
  background-color: rgb(255, 255, 255);
  overflow: auto;
}
.div-img {
  width: 8700px;
  /* height: 250px; */
  /* height: 200px; */
  /* overflow: auto; */
  /* overflow-x:scroll; */
  /* overflow-y: hidden; */
  /* float: left; */
  position: relative;
}
.imgs {
  width: 150px;
  height: 150px;
  float: left;
  margin: 16px;
  display: block;
}
.imgs:hover {
  transform: scale(1.3);
}
.diseases {
  float: left;
  display: block;
  margin-top: 195px;
  margin-left: -130px;
}
.ul {
  margin-top: 60px;
}
.li {
  margin-top: 10px;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 250px;
  height: 315px;
}
</style>
